package dao.impl;

import dao.UserDao;
import entity.User;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import utils.DataSourceUtils;

import java.sql.SQLException;
import java.util.List;

public class UserDaoImpl implements UserDao {

    private QueryRunner qr = new QueryRunner(DataSourceUtils.getDs());


    @Override
    public List<User> findPage(int start, int size) {
        try {
            return qr.query("SELECT * FROM USER LIMIT ?,?",new BeanListHandler<>(User.class),start,size);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    public long total() {
        try {
            return qr.query("select count(*) from user",new ScalarHandler<>());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public User findById(int id) {
        try {
            return qr.query("SELECT * FROM USER where id=?",new BeanHandler<>(User.class),id);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    public int update(User user) {
        String sql = "UPDATE USER SET NAME=?,gender=?,age=?,address=?,qq=?,email=?,bir=? WHERE id=?";
        Object[] params = {user.getName(),user.getGender(),user.getAge(),user.getAddress(),user.getQq(),user.getEmail(),user.getBir(),user.getId()};
        try {
            return qr.update(sql,params);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }
}
